package com.freight.order.serviceimpl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freight.base.utils.AreaAddressUtil;
import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.entity.User;
import com.freight.core.service.UserService;
import com.freight.msg.entity.Message;
import com.freight.msg.entity.MessageSend;
import com.freight.msg.service.MessageSendService;
import com.freight.msg.service.MessageService;
import com.freight.msg.utils.MyJPushClient;
import com.freight.order.dao.*;
import com.freight.order.dto.PcQuotationDto;
import com.freight.order.entity.*;
import com.freight.order.mapper.OrderGoodsVoMapper;
import com.freight.order.mapper.OrderMainMapper;
import com.freight.order.mapper.QuotationRecordMapper;
import com.freight.order.service.OrderOrderService;
import com.freight.order.service.PcQuotationRecordService;
import com.freight.order.vo.PlatQuotationRecordVo;
import com.freight.user.dao.VehicleLicenseDao;
import com.freight.user.entity.DriverUser;
import com.freight.user.mapper.DriverVoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
@Transactional
public class PcQuotationRecordServiceImpl implements PcQuotationRecordService {

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private OrderExtendDao orderExtendDao;

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageSendService messageSendService;

    @Autowired
    private UserService userService;

    @Autowired
    private VehicleLicenseDao vehicleLicenseDao;

    @Autowired
    private OrderOrderService orderOrderService;

    @Autowired
    private OrderOrderDao orderOrderDao;

    @Autowired
    private OrderMainMapper orderMainMapper;

    @Autowired
    private DriverVoMapper driverVoMapper;

    @Autowired
    private OrderGoodsVoMapper orderGoodsVoMapper;

    @Autowired
    private QuotationRecordDao quotationRecordDao;

    @Autowired
    private QuotationDetailsDao quotationDetailsDao;

    @Autowired
    private QuotationRecordMapper quotationRecordMapper;

    @Autowired
    private AreaAddressUtil areaAddressUtil;

    @Autowired
    private OrderGoodsDao orderGoodsDao;

    @Override
    public void entrustDriver(PcQuotationDto pcQuotationDto) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        User u = securityUtil.getCurrUser();
        if (!u.getUserType().equals(CommonConstant.USER_TYPE_COMPANY) && !u.getUserType().equals(CommonConstant.USER_TYPE_ADMIN)) {
            throw new FreightException("请先登入或者切换货主账号生成订单");
        }
        QuotationRecord quotationRecord=quotationRecordDao.getOne(pcQuotationDto.getQuotationRecordId());
        User u1 = userService.get(quotationRecord.getUserId());
        if(u1.getStatus() != 0){
            throw new FreightException("驾驶员账号被禁用");
        }
        OrderGoods orderGoods=orderGoodsDao.getOne(quotationRecord.getOrderGoodsId());

        List<QuotationDetails> details=quotationRecordMapper.getQuotationDetails(quotationRecord.getId());
        if(details == null || details.size()==0){
            throw new FreightException("操作出错");
        }
        QuotationDetails quotationDetails = details.get(0);
        if(orderGoods.getStatus() != 3){
            throw new FreightException("订单该状态下无法操作");
        }
//        GoodsLoadingTime goodsLoadingTime = orderGoodsVoMapper.getGoodsLoadingTime(quotationRecord.getOrderGoodsId(),quotationDetails.getLoadingTime());
//        if(goodsLoadingTime==null){
//            throw new FreightException("货源该时间段无法装车");
//        }
        //判断订单剩余重量和司机承运重量
        if (orderGoods.getGoodWeight()<pcQuotationDto.getGoodWeight()){
            throw new FreightException("货物不足");
        }
        List<Long> list=orderMainMapper.getHangintheairOrder(quotationRecord.getUserId());
        if (list!=null && list.size()!=0) {
            throw new FreightException("当前司机有未完成订单，不可委托");
        }
        DriverUser driverUser = driverVoMapper.getDriverVoUserId(quotationRecord.getUserId());
        if(driverUser.getVehicleId()==null){
            throw new FreightException("当前司机未绑定车辆");
        }
        OrderOrder orderOrder = new OrderOrder();
        OrderExtend orderExtend = new OrderExtend();
        ObjectUtil.copyPropertiesIgnoreNull(orderGoods,orderOrder);
        orderOrder.setDriverUnitPrice(orderGoods.getFreightUnitPrice());
        orderOrder.setDriverTotalPrice(orderGoods.getFreightUnitPrice().multiply(new BigDecimal(pcQuotationDto.getGoodWeight())));
        orderOrder.setVehicleId(driverUser.getVehicleId());
        orderOrder.setCompanyUserId(orderGoods.getCompanyUserId());
        orderOrder.setGoodsId(quotationRecord.getOrderGoodsId());
        orderOrder.setDriverUserId(quotationRecord.getUserId());
        orderOrder.setGoodWeight(pcQuotationDto.getGoodWeight());
        orderOrder.setTransGoodWeight(null);
        orderOrder.setRealGoodWeight(null);
        orderOrder.setOrderSource(quotationRecord.getOrderSource());
        orderOrder.setOrderState(0);
        orderOrder.setOrderStateDesc("待司机接单");
        orderOrder.setContent(pcQuotationDto.getContent());
        orderOrder.setId(null);

        orderGoods.setGoodWeight(orderGoods.getGoodWeight()-pcQuotationDto.getGoodWeight());
        if(orderGoods.getGoodWeight() == 0.0 ){
            orderGoods.setStatus(5);
        }
        orderGoodsDao.save(orderGoods);
        orderOrder=orderOrderDao.save(orderOrder);
        quotationRecord.setDriverState("2");
        quotationRecord.setOrderId(orderOrder.getId());
        quotationRecordDao.save(quotationRecord);
        orderExtend.setOrderId(orderOrder.getId());

        Date date= null;
        try {
            date = sdf.parse(quotationDetails.getLoadingTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        orderExtend.setEstimateLoadingTime(date);
        cal.add(Calendar.HOUR, orderOrder.getPrescription().intValue());
        orderExtend.setEstimateDischargeTime(cal.getTime());
        orderExtendDao.save(orderExtend);
        quotationDetails.setFreightUnitPrice(orderGoods.getFreightUnitPrice());
        quotationDetails.setFreightTotalPrice(orderOrder.getDriverTotalPrice());
        quotationDetails.setTransGoodWeight(pcQuotationDto.getGoodWeight());
        quotationDetails.setRemarks(pcQuotationDto.getContent());
        quotationDetailsDao.save(quotationDetails);

        User user = userService.get(orderOrder.getDriverUserId());

        String notificationTitle = "委托运单";
        String msgTitle = "委托运单";
        String msgContent = "您收到一个委托运单信息（装车时间："+sdf.format(orderExtend.getEstimateLoadingTime())+"，运单编号："+orderOrder.getOrderNo()+"）";
        Message message = new Message();
        message.setTitle(notificationTitle);
        message.setType("2");
        message.setTopicId("5");
        message.setContent(msgContent);
        message.setUserId(orderOrder.getDriverUserId());
        message=messageService.save(message);

        MessageSend messageSend=new MessageSend();
        messageSend.setUserId(orderOrder.getDriverUserId());
        messageSend.setMessageId(message.getId());
        messageSend.setType("2");
        messageSendService.save(messageSend);

         //极光推送
        MyJPushClient jPushUtil = new MyJPushClient();
        List<String> aliasList = Arrays.asList(user.getUsername());
        jPushUtil.sendToAliasList( aliasList,notificationTitle, msgTitle, msgContent, "3",null,null,orderOrder.getId(),1);

    }

    public static void main(String[] args) {
        Date date= null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            date = sdf.parse("2022-11-13 15:44:32");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, 1);
       System.out.println(cal.getTime());
    }

    @Override
    public List<QuotationDetails> quotationModifyList(Long quotationId) {
        User u = securityUtil.getCurrUser();
        Specification specification = new Specification<QuotationDetails>() {
            @Override
            public Predicate toPredicate(Root<QuotationDetails> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Long> quotationRecordId = root.get("quotationRecordId");
                List<Predicate> list = new ArrayList<Predicate>();
                list.add(cb.equal(quotationRecordId, quotationId));
                Predicate[] arr = new Predicate[list.size()];
                return query.where(list.toArray(arr)).getRestriction();
            }
        };
        return quotationDetailsDao.findAll(specification);
    }



    @Override
    public Page<PlatQuotationRecordVo> platformQuotationRecord(Long orderGoodsId, Page<PlatQuotationRecordVo> page) {
        User user=securityUtil.getCurrUser();

        Page<PlatQuotationRecordVo> list=quotationRecordMapper.platformQuotationPage(orderGoodsId,page);

        areaAddressUtil.fillAreaAddress(list.getRecords());

        return list;
    }

    @Override
    public Page<PlatQuotationRecordVo> companyplatformQuotationRecord(Long orderGoodsId, Page<PlatQuotationRecordVo> page) {
        User user=securityUtil.getCurrUser();

        Page<PlatQuotationRecordVo> list=quotationRecordMapper.companyplatformQuotationRecord(orderGoodsId,page,user.getId());

        areaAddressUtil.fillAreaAddress(list.getRecords());

        return list;
    }





}
